<?php
/**
 * 加载器
 */
namespace Hi;

class Loader{
    /**
     * Loader Instance
     * @var  Loader
     */
    protected static $_instance;
    /**
     * 获取实例
     * @return Loader 返回实例化的对象
     */
    public static function getInstance() {
        if (self::$_instance === NULL) {
            self::$_instance = new self();
        }
    }

    /**
     * Loader constructor
     */
    protected function __construct() {
        spl_autoload_register(array(
            __CLASS__,
            'Hi\Loader::autoload'
        ));
    }

    /**
     * 自动载入
     * @param string $class
     */
    public function autoload($class) {
        try {
            $this->loadClass($class);
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 载入类
     * @param $class
     * @return bool
     * @throws Exceptions
     */
    public static function loadClass($class) {
        $className = ltrim($class, '\\');
        $classPath = '';
        $namespace = '';
        $lastPos   = strripos($className, '\\');

        if ($lastPos !== false) {
            $namespace = substr($className, 0, $lastPos);
            $classPath = str_replace('\\', DS, $namespace);
            $name = strstr($namespace, '\\', true);

            if ($name == APP_NAMESPACE) {
                $classPath = APP_PATH . ltrim($classPath, APP_NAMESPACE);
            } else {
                $classPath = LIB_PATH . DS . $classPath;
            }
            $className = substr($className, $lastPos + 1);
        } else {
          $classPath = APP_PATH . DS . 'Model';
        }

        $classfile = $classPath . DS . $className . '.php';

        if (file_exists($classfile)) {
            include_once ($classfile);
        } else {
            throw new Exceptions('Library "' . $className . '" not found.');
        }
        return true;
    }
}